package com.ditri.distrident.service.impl;

import com.ditri.distrident.common.constant.ErrorCodeEnum;
import com.ditri.distrident.common.dto.request.AdminLoginReq;
import com.ditri.distrident.common.dto.response.AdminLoginResp;
import com.ditri.distrident.common.entity.Root;
import com.ditri.distrident.common.utils.CommonUtil;
import com.ditri.distrident.common.vo.RootVO;
import com.ditri.distrident.commonservice.service.RootService;
import com.ditri.distrident.service.AdminLoginService;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * @Author: edxuanlen
 * @Date: 2020/8/1:22:39
 */
@Service
public class AdminLoginServiceImpl implements AdminLoginService {

    private final RootService rootService;


    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public AdminLoginServiceImpl(RootService rootService) {
        this.rootService = rootService;
    }

    @Override
    public AdminLoginResp checkPassword(AdminLoginReq adminLoginReq) {

        System.out.println(adminLoginReq.toString());

        AdminLoginResp adminLoginResp = new AdminLoginResp();

        // 先在redis中查看， 拼接id 为 root_ + rootName
        Root root = (Root) redisTemplate.opsForValue().get("root_" + adminLoginReq.getRootName());

        // 如果查不到root
        if (CommonUtil.isEmpty(root)) {

            // 到数据库中查找
            root = rootService.queryByRootName(adminLoginReq.getRootName());
            // 查询不到用户信息
            if (CommonUtil.isEmpty(root)) {
                // 设置错误返回码
                adminLoginResp.setResult(ErrorCodeEnum.NO_SUCH_USER_ERROR.getResult());
                return adminLoginResp;
            }
            // 匹配密码
            boolean passwordMatch = BCrypt.checkpw(adminLoginReq.getRootPassword(), root.getRootPassword());

            // 如果密码不匹配
            if (!passwordMatch) {
                // 设置错误返回码
                adminLoginResp.setResult(ErrorCodeEnum.PASSWORD_ERROR.getResult());
                return adminLoginResp;
            }

            // 成功获取后，将对象序列化后塞进去redis
            redisTemplate.opsForValue().set("root_" + root.getRootName(), root);
        }

        // 将entity类型转化为vo 类型
        RootVO rootVo = new RootVO();
        assert root != null;
        BeanUtils.copyProperties(root, rootVo);
        adminLoginResp.setRootVo(rootVo);
        return adminLoginResp;
    }
}
